package com.xkw.demo.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class LoadController {
	
	/**
	 * 页面跳转
	 * @param map
	 * @return
	 */
	@RequestMapping("/load")
	public Object load(ModelMap map) {
		map.put("msg", "进入下载页");
		return "load";
	}
	/**
	 * 处理文件上传
	 */
	@RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
	@ResponseBody
	public String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		String fileName = file.getOriginalFilename();
	
		// 该路径可以从文件中读取，此处演示略
		String filePath = "D:/img/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
		System.err.println("上传路径:" + filePath);
		File dest = new File(filePath);
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdir();
		}
		try {
			file.transferTo(dest); // 保存文件
			System.err.println("上传成功");
		} catch (Exception e) {
			//e.printStackTrace();
			System.err.println("上传失败");
		}
		return null;
	}

	@RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
	public String downloadFile(HttpServletResponse response) {
		String filePathName = "D:/img/download.jpg";
		response.reset();
		response.setHeader("Content-Disposition", "attachment;fileName=" + filePathName);
		try {
			InputStream inStream = new FileInputStream(filePathName);
			OutputStream os = response.getOutputStream();

			byte[] buff = new byte[1024];
			int len = -1;
			while ((len = inStream.read(buff)) > 0) {
				os.write(buff, 0, len);
			}
			os.flush();
			os.close();
			inStream.close();
			System.err.println("文件下载成功");
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("文件下载失败");	
		}
		return null;
	}

}
